$(function() {

    'use strict';

    var shareSDK   = commonJs.shareSDK;
    var imgLoader  = commonJs.imgLoader;
    var audio      = commonJs.audio;
    var socket     = commonJs.socket;
    var eventPool  = commonJs.eventPool;
    var utils      = commonJs.utils;
    var coverCloud = commonJs.coverCloud;
    var camera     = commonJs.camera;
    var starArea   = commonJs.starArea;
    var girl       = commonJs.girl;

    var cmdControl = {

        _parseCmd: function(cmdString) {
            var cmdArr = cmdString.split('+++');
            return {
                cmd  : cmdArr[0],
                data : cmdArr[1]
            }
        },

        stop: function() {
            socket.stopListening();
        },

        start: function() {

            var that = this;

            socket.listen(function(cmdString) {

                var cmdObj = that._parseCmd(cmdString),
                    cmd    = cmdObj.cmd,
                    data   = cmdObj.data;

                if (cmd === 'reload') {
                    window.location.reload();

                } else if (cmd === 'start') {
                    eventPool.trigger('CMD_FRIEND_READY');

                } else if (cmd === 'play') {

                    if (data === 'SOCK_STAR_START_PLAY') {
                        eventPool.trigger('CMD_STAR_START');

                    } else if (data === 'SOCK_STAR_STAR_ACCROSS') {
                        eventPool.trigger('CMD_STAR_ACCROSS');

                    } else if (data === 'SOCK_OP_DONE_W1') {
                        eventPool.trigger('CMD_OP_DONE_W1');

                    } else if (data.match(/SOCK_OP_W2_SELECT_/)) {
                        eventPool.trigger('CMD_W2_SELECT', data.substr(18));

                    } else if (data.match(/SOCK_SEA_EXIT/)) {
                        eventPool.trigger('CMD_SEA_EXIT');

                    } else {
                        // Do nothing
                    }

                } else {
                    // Do nothing
                }
            });

            return this;
        },

        init: function() {

            socket.init(function() {

                // 生成clientid并生成二维码
                var id = new Date().getTime() + 'zichen' +
                         Math.floor(Math.random() * 999999);

                if (utils.getQueryString('idfortest')) {
                    id = 1234;
                }

                socket.send('register', id);

                // 生成二维码
                var currLink = window.location.href,
                    friendLink = currLink.substr(0, currLink.lastIndexOf('/') + 1) +
                            'friend.html?id=' + id;

                $('.page-star .content img').attr('src',
                        'http://qrcode2.webapp.163.com/l?d=' +
                        encodeURIComponent(friendLink));
            });

            eventPool.one('STAR_STAR_EXIT', function() {
                socket.send('play', 'SOCK_STAR_STAR_EXIT');
            }, this);

            eventPool.on('OP_W2_SELECT', function(data) {
                socket.send('play', 'SOCK_OP_W2_SELECT_' + data);
            }, this);

            eventPool.one('SEA_EXIT', function() {
                socket.send('play', 'SOCK_SEA_EXIT');
            }, this);

            return this;
        }
    };

    // add DeviceMotion功能集合
    function DMotion(options) {
        this.init(options);
    }

    DMotion.prototype = {
        // 摇一摇阈值
        SHAKE_THRESHOLD: 1500,
        // 翻转阈值
        TURN_THRESHOLD: 200,
        // 取得数据间隔
        _GET_DATA_INTERVAL: 200,
        merge: function(o, n) {
            for (var i in n) {
                if (!o.hasOwnProperty(n[i])) o[i] = n[i];
            }
            return o;
        },
        init: function(options) {
            var defaultParam = {
                shake: function() {},
                tilt: function() {},
                turn: function() {}
            };
            var self = this;
            self.params = options || {};

            self.params = this.merge(defaultParam, self.params);

            // 是否开始获取数据
            self._getData = false;
            // 保存上一次的motion
            self.last = {};
            // 保存本次motion
            self.cur = {
                acceleration: {},
                accelerationIncludingGravity: {},
                rotationRate: {}
            }


            // 初始化临时参数
            self.__param = {
                shakeParam: {}
            };
            if (window.DeviceMotionEvent) {
                window.addEventListener('devicemotion', function(event) {
                    self.onDeviceMotion.call(self, event)
                });

                self._startCount();
            } else {
                alert('your browser is not support devicemotion event!');
            }
        },
        /**
         * 开始计时去取数据
         * @return {[type]} [description]
         */
        _startCount: function() {
            var self = this;

            self._timer = setInterval(function() {
                self._getData = true;

                self.shake.call(self);
                self.tilt.call(self);
                self.turn.call(self);

            }, self._GET_DATA_INTERVAL)
        },
        destory: function() {
            var self = this;

            clearInterval(self._timer);
        },
        // 摇一摇
        shake: function() {

            var self = this,
                LAIG = self.last.accelerationIncludingGravity,
                AIG = self.cur.accelerationIncludingGravity;
            var x = 0,
                y = 0,
                z = 0;
            var last_x = LAIG.x || 0,
                last_y = LAIG.y || 0,
                last_z = LAIG.z || 0;

            x = AIG.x;
            y = AIG.y;
            z = AIG.z;


            var speed = Math.abs(x + y + z - last_x - last_y - last_z) / self._GET_DATA_INTERVAL * 10000;
            // debugBar.show(speed);

            if (speed > self.SHAKE_THRESHOLD) {
                self.params.shake.call(self, speed)
            }
        },
        // 倾斜
        tilt: function() {
            var self = this,
                AIG = self.cur.accelerationIncludingGravity;

            self.params.tilt.call(self, AIG)
        },
        // 旋转
        // 2015.6.16 三星note2微信6.2 rotationRate中值为空
        turn: function() {
            var self = this,
                RR = self.cur.rotationRate,
                LRR = self.last.rotationRate,
                rs = {};

            if (RR.alpha < 0 && RR.alpha - LRR.alpha < 0 && RR.alpha - LRR.alpha < -1 * self.TURN_THRESHOLD) {
                // output('turn forward')
            }

            if (RR.alpha - LRR.alpha > 0 && RR.alpha - LRR.alpha > self.TURN_THRESHOLD) {
                // output(RR.alpha + ' turn back ' + LRR.alpha)
            }
        },
        _setDeviceMotionData: function(motion) {
            var self = this;

            self.last = self.cur;

            self.cur = motion;


            self.acceleration = motion.acceleration;
            self.accelerationIG = motion.accelerationIncludingGravity;
            self.rotationRate = motion.rotationRate;



        },
        onDeviceMotion: function(event) {
            var self = this;


            if (self._getData) {
                self._getData = false;
                self._setDeviceMotionData(event)
            }

        }
    }

    var homePage = {

        _onShake: function() {
            utils.hideItem($('.page-home .shake-tip'), 500);
            setTimeout(function() {
                girl.wakeup();
            }, 2000);
            setTimeout(function() {
                utils.hideItem($('.girl'), 2000);
            }, 5000);
            setTimeout(function() {
                utils.hideItem($('.page-home'), 1000, function() {
                    $('.page-home').remove();
                    cmdControl.start();
                });
            }, 7000);
            return this;
        },

        startListening: function() {

            var motion,
                that = this;

            setTimeout(function() {
                utils.showItem($('.page-home .shake-tip'), 500);
            }, 2000);

            // setTimeout(function() {
            //     that._onShake();
            // }, 4000);
            // return this;

            motion = new DMotion({
                shake: function() {
                    that._onShake();
                    motion.destory();
                }
            });

            return this;
        }
    };

    var starPage = {

        _el: $('.wrapper .page-star'),

        exit: function(callback) {
            var that = this;
            utils.moveItem(this._el.find('.scene'), 600, 3000, function() {
                utils.hideItem(that._el, 1000, function() {
                    that._el.remove();
                });
                callback && callback();
            });
            return this;
        },

        flyAccorss: function(callback) {
            girl.flyOut(5000);
            utils.moveItem(this._el.find('.scene'), 400, 6000, function() {
                callback && callback();
            });
            return this;
        },

        showDot: function(callback) {
            utils.showItem(this._el.find('.dot'), 1000);
            return this;
        },

        hideCurtain: function(callback) {
            var that = this;
            utils.hideItem(this._el.find('.star-tip, .drag-tip'), 1000, function() {
                that._el.find('.curtain').attr('style',
                        '-webkit-transform:translateY(-1136px);' +
                        '-webkit-transition:all 1s;');
                setTimeout(function() {
                    girl.reset().flyIn(6000);
                    callback && callback();
                }, 1000);
            });
            return this;
        },

        showStarAndTip: function(callback) {
            starArea.show();
            utils.showItem(this._el.find('.star-tip'), 1000, function() {
                callback && callback();
            });
            return this;
        },

        hideContent: function(callback) {
            utils.hideItem(this._el.find('.content'), 2000, function() {
                callback && callback();
            });
            return this;
        },

        init: function() {

            var that = this;

            eventPool.one('CMD_FRIEND_READY', function() {
                this.hideContent(function() {
                    that.showStarAndTip();
                });
            }, this);

            eventPool.one('CMD_STAR_START', function() {
                this.hideCurtain();
            }, this);

            eventPool.one('CMD_STAR_ACCROSS', function() {
                this.flyAccorss(function() {
                    that.showDot();
                });
            }, this);

            eventPool.one('STAR_STAR_EXIT', function() {
                this.exit(function() {
                    eventPool.trigger('STAR_STAR_END');
                });
            }, this);

            this._el.find('.dot').click(function() {
                utils.hideItem($(this), 1000, function() {
                    eventPool.trigger('STAR_STAR_EXIT');
                });
            });

            return this;
        }
    };

    var seaPage = {

        _el      : $('.wrapper .page-sea'),
        _sceneEl : $('.wrapper .page-sea .scene'),

        _selfReady   : false,
        _friendReady : false,

        playFirework: function(callback) {
            var that = this;
            utils.hideItem(this._el.find('.word'), 2000, function() {
                that._el.find('.yanhua').show().addClass('show');
            });
            setTimeout(function() {
                utils.hideItem(that._el, 1000, function() {
                    $('.wrapper').remove();
                });
                callback && callback();
            }, 8000);
            return this;
        },

        showWords: function(callback) {
            starArea.hide();
            camera.zoomIn(this._el, 1.5, 50, 0, 2);
            utils.showItem(this._el.find('.word'), 2000);
            setTimeout(function() {
                callback && callback();
            }, 3000);
            return this;
        },

        flyToZhongguo: function(callback) {
            utils.moveItem(this._sceneEl, 7685, 15000, function() {
                callback && callback();
            });
            return this;
        },

        flyToTaiwan: function(callback) {
            utils.moveItem(this._sceneEl, 4670, 15000, function() {
                callback && callback();
            });
            coverCloud.show();
            girl.flyOut(12500);
            setTimeout(function() {
                girl.change()
            }, 1000);
            return this;
        },

        flyToHanguo: function(callback) {
            utils.moveItem(this._sceneEl, 1880, 10000, function() {
                callback && callback();
            });
            girl.reset().flyIn(10000);
            return this;
        },

        init: function() {

            var that = this;

            eventPool.one('STAR_STAR_END', function() {
                this.flyToHanguo(function() {
                    eventPool.trigger('SEA_ARRIVE_HANGUO');
                });
            }, this);

            eventPool.one('CMD_OP_DONE_W1', function() {
                eventPool.trigger('OP_DONE_W1');
                this.flyToTaiwan(function() {
                    eventPool.trigger('SEA_ARRIVE_TAIWAN');
                });
            }, this);

            eventPool.one('OP_DONE_W2', function() {
                this.flyToZhongguo(function() {
                    eventPool.trigger('SEA_ARRIVE_ZHONGGUO');
                });
            }, this);

            eventPool.one('SEA_PLAY_FIREWORK', function() {
                this.playFirework();
            }, this);

            eventPool.one('OP_DONE_W3', function() {
                this.showWords(function() {
                    that._selfReady = true;
                    eventPool.trigger('SEA_EXIT');

                    if (that._friendReady) {
                        eventPool.trigger('SEA_PLAY_FIREWORK');
                    }
                });
            }, this);

            eventPool.one('CMD_SEA_EXIT', function() {
                if (this._selfReady) {
                    eventPool.trigger('SEA_PLAY_FIREWORK');
                } else {
                    this._friendReady = true;
                }
            }, this);

            return this;
        }
    };

    // Init

    audio.init(__CDNPATH + '/data/music.mp3');

    camera.zoomIn($('.wrapper'), 1.3, 50, 40);

    starPage.init();
    seaPage.init();
    cmdControl.init();

    var loadList1 = [],
        loadList2 = [],
        list1 = $('#preload_list1 img'),
        list2 = $('#preload_list2 img');

    for (var i = list1.length; i--;) {
        loadList1.push(list1.eq(i).data('src'));
    }
    for (var i = list2.length; i--;) {
        loadList2.push(list2.eq(i).data('src'));
    }

    // 加载loading页面
    imgLoader.reset(loadList1, function() {

        $('#loading-cover').fadeOut(1000, function() {

            $('#loading-cover').remove();
            $('.page-home .loading-tip').fadeIn(500);

            girl.showSleep();

            // 二次加载资源
            imgLoader.reset(loadList2, function() {

                setTimeout(function() {
                    camera.zoomBack($('.wrapper'), 3);
                    homePage.startListening();
                }, 1500);

                $('.page-home .loading-tip').fadeOut(500, function() {
                    $(this).remove();
                });

            }, function(pct) {
                $('.page-home .loading-tip span').html(pct);
            }).load();
        });

    }).load();
});
